package cn.wolfcode.business.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.wolfcode.business.domain.BpmnInfo;
import cn.wolfcode.business.domain.CarPackageAudit;
import cn.wolfcode.business.mapper.BpmnInfoMapper;
import cn.wolfcode.business.mapper.CarPackageAuditMapper;
import cn.wolfcode.business.vo.AuditInfoVO;
import cn.wolfcode.business.vo.AuditVO;
import cn.wolfcode.common.core.domain.entity.SysUser;
import cn.wolfcode.common.exception.ServiceException;
import cn.wolfcode.common.utils.DateUtils;
import cn.wolfcode.common.utils.SecurityUtils;
import cn.wolfcode.system.service.ISysConfigService;
import cn.wolfcode.system.service.ISysRoleService;
import cn.wolfcode.system.service.ISysUserService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;
import org.apache.catalina.security.SecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;
import cn.wolfcode.business.mapper.ServiceItemMapper;
import cn.wolfcode.business.domain.ServiceItem;
import cn.wolfcode.business.service.IServiceItemService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

/**
 * 服务项Service业务层处理
 * 
 * @author dafei
 * @date 2023-10-29
 */
@Service
public class ServiceItemServiceImpl implements IServiceItemService 
{
    @Autowired
    private ServiceItemMapper serviceItemMapper;

    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysRoleService sysRoleService;

    @Autowired
    private CarPackageAuditMapper carPackageAuditMapper;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private BpmnInfoMapper bpmnInfoMapper;


    /**
     * 查询服务项
     * 
     * @param id 服务项主键
     * @return 服务项
     */
    @Override
    public ServiceItem selectServiceItemById(Long id)
    {
        return serviceItemMapper.selectServiceItemById(id);
    }

    /**
     * 查询服务项列表
     * 
     * @param serviceItem 服务项
     * @return 服务项
     */
    @Override
    public List<ServiceItem> selectServiceItemList(ServiceItem serviceItem)
    {
        return serviceItemMapper.selectServiceItemList(serviceItem);
    }

    /**
     * 新增服务项
     * 
     * @param serviceItem 服务项
     * @return 结果
     */
    @Override
    public int insertServiceItem(ServiceItem serviceItem)
    {
        //判断参数合法性--是否为空
        if(serviceItem == null){
            throw new ServiceException("参数异常");
        }
        //判断参数合法性--折扣价小于原价
        int ret = serviceItem.getDiscountPrice().compareTo(serviceItem.getOriginalPrice());
        if(ret > 0){
            throw new ServiceException("折扣价不能大于原价~");
        }
        // 默认状态设置
        //上下架状态---重要属性建议明确设置
        serviceItem.setSaleStatus(ServiceItem.SALESTATUS_OFF);
        //审核状态
        // 1>是套餐---初始化
        // 1>非套餐---无需审核
        if (ServiceItem.CARPACKAGE_YES.equals(serviceItem.getCarPackage())){
            //套餐
            serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_INIT);
        }else{
            //非套餐
            serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_NO_REQUIRED);
        }
        //创建时间
        serviceItem.setCreateTime(DateUtils.getNowDate());
        return serviceItemMapper.insertServiceItem(serviceItem);
    }

    /**
     * 修改服务项
     * 
     * @param serviceItem 服务项
     * @return 结果
     */
    @Override
    public int updateServiceItem(ServiceItem serviceItem)
    {
        //参数校验
        //价格校验
        //判断参数合法性--是否为空
        if(serviceItem == null){
            throw new ServiceException("参数异常");
        }
        //判断参数合法性--折扣价小于原价
        int ret = serviceItem.getDiscountPrice().compareTo(serviceItem.getOriginalPrice());
        if(ret > 0){
            throw new ServiceException("折扣价不能大于原价~");
        }
        //考虑编辑状态
        //1> 审核中  上架
        ServiceItem item = serviceItemMapper.selectServiceItemById(serviceItem.getId());
        if(ServiceItem.AUDITSTATUS_AUDITING.equals(item.getAuditStatus())
                || ServiceItem.SALESTATUS_ON.equals(item.getSaleStatus())){
            throw new ServiceException("服务项在审核中或者上架状态不允许修改");
        }
        //修改之后状态变化怎么考虑?
        //单项--无需审核状态
        //套餐--初始化状态
        if(ServiceItem.CARPACKAGE_YES.equals(item.getCarPackage())){
            serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_INIT);
        }

        //@TODO 单项不能转换套餐
        if(!item.getCarPackage().equals(serviceItem.getCarPackage())){
            throw new ServiceException("服务单项不能与套餐相互转换");
        }
        return serviceItemMapper.updateServiceItem(serviceItem);
    }

    /**
     * 批量删除服务项
     * 
     * @param ids 需要删除的服务项主键
     * @return 结果
     */
    @Override
    public int deleteServiceItemByIds(Long[] ids)
    {
        return serviceItemMapper.deleteServiceItemByIds(ids);
    }

    /**
     * 删除服务项信息
     * 
     * @param id 服务项主键
     * @return 结果
     */
    @Override
    public int deleteServiceItemById(Long id)
    {
        return serviceItemMapper.deleteServiceItemById(id);
    }

    @Override
    public void saleOn(Long id) {

        //参数校验--id 不为空, 状态为未上架状态
        ServiceItem serviceItem = serviceItemMapper.selectServiceItemById(id);
        if(serviceItem == null || ServiceItem.SALESTATUS_ON.equals(serviceItem.getSaleStatus())){
            throw  new ServiceException("参数异常");
        }
        //满足上架条件判断--
        //套餐--审核通过
       /* if(ServiceItem.CARPACKAGE_YES.equals(serviceItem.getCarPackage()) &&
                ServiceItem.AUDITSTATUS_APPROVED.equals(serviceItem.getAuditStatus())
        ){
            //允许上架
            serviceItem.setSaleStatus(ServiceItem.SALESTATUS_ON);
        }*/
        //允许上架的条件: 审核通过 || 无需审核
        if(!(ServiceItem.AUDITSTATUS_NO_REQUIRED.equals(serviceItem.getAuditStatus())
            || ServiceItem.AUDITSTATUS_APPROVED.equals(serviceItem.getAuditStatus()))){
            throw  new ServiceException("必须是审核通过或者无需审核才允许上架");
        }
        //单项--直接上架
        //直接上架-状态改为上架
        serviceItem.setSaleStatus(ServiceItem.SALESTATUS_ON);
        serviceItemMapper.updateServiceItem(serviceItem);
    }

    @Override
    public void saleOff(Long id) {
        //参数校验--id 不为空, 状态为上架状态
        ServiceItem serviceItem = serviceItemMapper.selectServiceItemById(id);
        if(serviceItem == null || !ServiceItem.SALESTATUS_ON.equals(serviceItem.getSaleStatus())){
            throw  new ServiceException("参数异常");
        }

        //下架
        serviceItem.setSaleStatus(ServiceItem.SALESTATUS_OFF);
        serviceItemMapper.updateServiceItem(serviceItem);

    }

    @Override
    public AuditInfoVO auditInfo(Long id) {
        ServiceItem serviceItem = serviceItemMapper.selectServiceItemById(id);
        if(serviceItem == null){
            throw new ServiceException("参数异常");
        }
        AuditInfoVO vo = new AuditInfoVO();
        //审核套餐信息
        vo.setServiceItem(serviceItem);
        //店长角色下用户列表
        List<SysUser>  shopOwners = sysUserService.queryByRoleKey("shopOwner");
        vo.setShopOwners(shopOwners);
        //财务角色下用户列表
        List<SysUser>  finances = sysUserService.queryByRoleKey("finance");
        vo.setFinances(finances);
        //金额限制
        String priceLimit = sysConfigService.selectConfigByKey("discountPriceLimit");
        if(!StringUtils.hasText(priceLimit)){
            priceLimit = "3000";
        }
        vo.setDiscountPrice(new BigDecimal(priceLimit));
        return vo;
    }

    @Transactional
    @Override
    public void startAudit(AuditVO vo) {

        //参数判断
        ServiceItem serviceItem = serviceItemMapper.selectServiceItemById(vo.getId());
        if(serviceItem == null){
            throw new ServiceException("参数异常");
        }

        if(!ServiceItem.CARPACKAGE_YES.equals(serviceItem.getCarPackage())){
            throw new ServiceException("必须是套餐才允许审核");
        }
        if(!(ServiceItem.AUDITSTATUS_INIT.equals(serviceItem.getAuditStatus())
                || ServiceItem.AUDITSTATUS_REPLY.equals(serviceItem.getAuditStatus()))){
            throw new ServiceException("必须是初始化或者审核拒绝状态才可以进行审核");
        }
        //审核信息保存
        CarPackageAudit audit = new CarPackageAudit();

        audit.setInfo(vo.getInfo());
        audit.setServiceItemId(vo.getId());
        audit.setServiceItemName(serviceItem.getName());
        audit.setServiceItemInfo(serviceItem.getInfo());
        audit.setServiceItemPrice(serviceItem.getDiscountPrice());
        audit.setCreatorId(SecurityUtils.getUserId().toString());
        audit.setStatus(CarPackageAudit.STATUS_IN_ROGRESS);
        audit.setCreateTime(new Date());
        carPackageAuditMapper.insertCarPackageAudit(audit);

        BpmnInfo bpmnInfo = bpmnInfoMapper.selectLastByType(CarPackageAudit.FLOW_AUDIT_TYPE);
        //流程启动---businesskey   map(审核流程涉及参数)

        String businessKey = audit.getId().toString();
        String processDefinitionKey = bpmnInfo.getProcessDefinitionKey();
        Map<String, Object> map = new HashMap<>();

        //设置节点审核人:财务
        if(vo.getFinanceId() != null){
            map.put("financeId", vo.getFinanceId());
        }
        //设置节点审核人:店长
        if(vo.getShopOwnerId() != null){
            map.put("shopOwnerId", vo.getShopOwnerId());
        }
        // 流程图中不支持BigDecimal 校验, 转换long类型
        map.put("disCountPrice", serviceItem.getDiscountPrice().longValue());

        ProcessInstance instance = runtimeService.startProcessInstanceByKey(processDefinitionKey, businessKey, map);

        //audit.setInstanceId(instance.getProcessInstanceId());  //流程实例id
        audit.setInstanceId(instance.getId());  //流程实例id
        carPackageAuditMapper.updateCarPackageAudit(audit);

        //套餐项状态--审核中
        serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_AUDITING);
        serviceItemMapper.updateServiceItem(serviceItem);

    }
}
